package com.chenyue.cm.match.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.account.service.JdAccountService;
import com.chenyue.cm.account.vo.AccountSource;
import com.chenyue.cm.account.vo.IntegralSource;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.common.constant.ConstantValues;
import com.chenyue.cm.common.dao.JdConstantValuesMapper;
import com.chenyue.cm.common.domain.JdConstantValues;
import com.chenyue.cm.match.dao.JdMatchGroupMapper;
import com.chenyue.cm.match.dao.JdMatchGroupUserMapper;
import com.chenyue.cm.match.dao.JdMatchMapper;
import com.chenyue.cm.match.dao.JdMatchSignMapper;
import com.chenyue.cm.match.domain.JdMatch;
import com.chenyue.cm.match.domain.JdMatchGroup;
import com.chenyue.cm.match.domain.JdMatchGroupUser;
import com.chenyue.cm.match.domain.JdMatchSign;
import com.chenyue.cm.match.service.JdMatchSignService;
import com.chenyue.cm.order.domain.JdOrder;
import com.chenyue.cm.user.dao.JdAppUserMapper;
import com.chenyue.cm.user.dao.JdUserInviteMapper;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdUserInvite;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author chenyue-cm
 */
@Service(value = "JdMatchSignService")
public class JdMatchSignServiceImpl extends BaseServiceImpl<JdMatchSign> implements JdMatchSignService {

    private final JdMatchSignMapper jdMatchSignMapper;

    private final JdMatchGroupMapper groupMapper;

    private final JdMatchGroupUserMapper groupUserMapper;

    private final JdConstantValuesMapper constantValuesMapper;

    private final JdUserInviteMapper userInviteMapper;

    private final JdAccountService accountService;

    private final JdMatchMapper jdMatchMapper;

    private final JdAppUserMapper appUserMapper;


    public JdMatchSignServiceImpl(
            @Qualifier("jdMatchSignMapper") JdMatchSignMapper jdMatchSignMapper,
            @Qualifier("jdMatchGroupMapper") JdMatchGroupMapper groupMapper,
            @Qualifier("jdMatchGroupUserMapper") JdMatchGroupUserMapper groupUserMapper,
            @Qualifier("jdConstantValuesMapper") JdConstantValuesMapper constantValuesMapper,
            @Qualifier("jdUserInviteMapper") JdUserInviteMapper userInviteMapper,
            @Qualifier("jdMatchMapper") JdMatchMapper jdMatchMapper,
            @Qualifier("jdAppUserMapper") JdAppUserMapper appUserMapper,
            JdAccountService accountService

    ) {
        this.jdMatchSignMapper = jdMatchSignMapper;
        this.groupMapper = groupMapper;
        this.groupUserMapper = groupUserMapper;
        this.constantValuesMapper = constantValuesMapper;
        this.userInviteMapper = userInviteMapper;
        this.accountService = accountService;
        this.jdMatchMapper = jdMatchMapper;
        this.appUserMapper = appUserMapper;
    }

    @Override
    @Resource(name = "jdMatchSignMapper")
    public void setBaseMapper(LcBaseMapper<JdMatchSign, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    /**
     * 更新报名 支付状态 & 邀请码金币返利
     *
     * @param order 订单
     */
    @Override
    public void updateSignAndGoldBack(JdOrder order) {
        final Integer userId = order.getUserId();
        final JdMatchGroup group = groupMapper.selectOne(
                new LambdaQueryWrapper<JdMatchGroup>()
                        .eq(JdMatchGroup::getMatchId, order.getProductId())
                        .eq(JdMatchGroup::getLeader, order.getUserId())
        );
        // 参赛给积分
        final JdMatch jdMatch = jdMatchMapper.selectById(order.getProductId());
        if (group == null) {
//            个人报名
            final JdMatchSign matchSign = jdMatchSignMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchSign>()
                            .eq(JdMatchSign::getUserId, order.getUserId())
                            .eq(JdMatchSign::getMatchId, order.getProductId())
            );
            matchSign.setPayState(1);
            jdMatchSignMapper.updateById(matchSign);
            //参赛给积分
            accountService.integralRecharge(order.getUserId(),jdMatch.getIntegral(), IntegralSource.COMPETITON,order.getProductId().toString(),"参赛获得积分");
        } else {
//            团队报名
            final List<Integer> userIdList = groupUserMapper.selectList(
                    new LambdaQueryWrapper<JdMatchGroupUser>()
                            .eq(JdMatchGroupUser::getGroupId, group.getId())
            ).stream().map(JdMatchGroupUser::getUserId).collect(Collectors.toList());
//            团队每个人都需要改成已支付
            for (Integer id : userIdList) {
                final JdMatchSign matchSign = jdMatchSignMapper.selectOne(
                        new LambdaQueryWrapper<JdMatchSign>()
                                .eq(JdMatchSign::getUserId, id)
                                .eq(JdMatchSign::getMatchId, order.getProductId())
                );
                matchSign.setPayState(1);
                jdMatchSignMapper.updateById(matchSign);
                //参赛给积分
                accountService.integralRecharge(id,jdMatch.getIntegral(), IntegralSource.COMPETITON,order.getProductId().toString(),"参赛获得积分");
            }
        }
        final JdUserInvite jdUserInvite = userInviteMapper.selectOne(
                new LambdaQueryWrapper<JdUserInvite>()
                        .eq(JdUserInvite::getReceiveUser, userId)
                        .last(" limit 1")
        );
        if (jdUserInvite != null ) {
            final JdAppUser jdAppUser = appUserMapper.selectById(jdUserInvite.getSendUser());
            if (jdAppUser != null){
                //            给邀请人返利
                order.setUserId(jdUserInvite.getSendUser());
                goldBack(order);
            }
        }
    }

    private void goldBack(JdOrder order) {
        JdConstantValues constantValues = constantValuesMapper.selectOne(
                new LambdaQueryWrapper<JdConstantValues>()
                        .eq(JdConstantValues::getConstantKey, ConstantValues.CALL_BACK_RATE)
        );
//        返利比率
        Double callBackRate = Double.valueOf(constantValues.getConstantValue());

        double backValue = order.getOrderAmount() * callBackRate;
        accountService.recharge(order.getUserId(), backValue, AccountSource.INVITE_BACK, order.getId());

    }
}
